package com.ruoyi.generator.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.vo.SysMenuVo;
import com.ruoyi.common.core.domain.entity.vo.SysRoleVo;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.generator.domain.FromBuildConfig;
import com.ruoyi.generator.domain.GenForm;
import com.ruoyi.generator.domain.vo.GenFormVo;
import com.ruoyi.generator.service.IFromBuildConfigService;
import com.ruoyi.generator.service.IFromCrudBtnsService;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.service.impl.FromBuildConfigServiceImpl;
import com.ruoyi.generator.service.impl.FromCrudBtnsServiceImpl;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 单设计_配置Controller
 *
 * @author XL
 * @date 2022-08-05 12:01:23
 */
@RestController
@RequestMapping("/tool/gen/FromBuildConfig")
public class FromBuildConfigController extends BaseController {
    @Autowired
    private IFromBuildConfigService fromBuildConfigService;

    @Autowired
    private FromBuildConfigServiceImpl fromBuildConfigServiceImpl;

    @Autowired
    private FromCrudBtnsServiceImpl fromCrudBtnsService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IGenTableService genTableService;

    /**
     * 获取字段信息
     *
     * @return
     */
    @GetMapping("/init")
    public AjaxResult getFieldInfo() {
        return fromBuildConfigService.getColumnConfigByTableName("sys_from_build_config");
    }

    /**
     * 查询单设计_配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(FromBuildConfig fromBuildConfig) {
        try {
            startPage();
            List<FromBuildConfig> list = fromBuildConfigService.selectFromBuildConfigList(fromBuildConfig);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口list异常", e);
            return null;
        }
    }

    /**
     * 导出单设计_配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:export')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FromBuildConfig fromBuildConfig) {
        try {
            List<FromBuildConfig> list = fromBuildConfigService.selectFromBuildConfigList(fromBuildConfig);
            ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
            return util.exportExcel(list, "FromBuildConfig");
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口export异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 导入单设计_配置列表
     */

    /**
     * 获取单设计_配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,
                              @RequestParam(value = "clientType", defaultValue = "PC") String clientType) {
        try {
            Map<String, Object> result = new HashMap<>();
            //表单数据
            result.put("data", fromBuildConfigService.selectFromBuildConfigById(id));
            //表单设计字段配置信息
            result.put("formBuildConfig", fromBuildConfigService.getFormBuildConfig("FromBuildConfig", clientType));
            //返回结果
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口getInfo异常", e);
            return AjaxResult.error("获取异常");
        }
    }

    /**
     * 新增单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:add')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FromBuildConfig fromBuildConfig) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            fromBuildConfig.setCreateBy(loginUser.getUsername());
            fromBuildConfig.setCreateTime(new Date());
            return toAjax(fromBuildConfigService.insertFromBuildConfig(fromBuildConfig));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口add异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 修改单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:edit')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FromBuildConfig fromBuildConfig) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            fromBuildConfig.setUpdateBy(loginUser.getUsername());
            fromBuildConfig.setUpdateTime(new Date());
            return toAjax(fromBuildConfigService.updateFromBuildConfig(fromBuildConfig));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口edit异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:remove')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            return toAjax(fromBuildConfigService.deleteFromBuildConfigByIds(ids));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口remove异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
        List<FromBuildConfig> dataList = util.importExcel(file.getInputStream());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        String operName = loginUser.getUsername();
        int successCount = 0;
        for (FromBuildConfig item : dataList) {
            successCount += fromBuildConfigService.insertFromBuildConfig(item);
        }
        String result = StringUtils.format("导入成功条数:{}，失败条数：{}", successCount, (dataList.size() - successCount));
        return AjaxResult.success(result);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
        return util.importTemplateExcel("单设计_配置");
    }

    /**
     * ============================================================================
     */

    /**
     * 获取表单设计字段配置信息
     *
     * @param confParams
     * @return
     */
    @PostMapping(value = "/getFormBuildConfig")
    public AjaxResult getFormBuildConfig(@RequestBody Map<String, Object> confParams) {
        if (confParams == null || confParams.size() <= 0) {
            return AjaxResult.error("操作失败，参数获取异常");
        }
        return fromBuildConfigService.getFormBuildConfig(confParams);
    }

    /**
     * 获取表单设计字段配置信息
     *
     * @param confParams
     * @return
     */
    @PostMapping(value = "/getFormComponentConfig")
    public AjaxResult getFormComponentConfig(@RequestBody Map<String, Object> confParams) {
        if (confParams == null || confParams.size() <= 0) {
            return AjaxResult.error("操作失败，参数获取异常");
        }
        return fromBuildConfigService.getFormComponentConfig(confParams);
    }

    /**
     * 根据数据库表名获取对应CRUD配置信息，按钮配置、表单配置
     * @returnT
     */
    @GetMapping("CrudConfig/{buildKey}")
    public AjaxResult getCrudConfigByBuildKey(@PathVariable("buildKey") String buildKey) throws Exception {
        if(StringUtils.isEmptyIncludeNull(buildKey)){
            return AjaxResult.success();
        }
        /**
         * 获取表单配置信息
         */
        Map<String, Object> confParams = new HashMap<>();
        confParams.put("formBuildKey",buildKey);
        AjaxResult formBuildConfig = fromBuildConfigService.getFormBuildConfig(confParams);
        if(formBuildConfig.isError()){
            return formBuildConfig;
        }
        /**
         * 组装结果
         */
        Map<String,Object> configs = null;
        Object data = formBuildConfig.get(AjaxResult.DATA_TAG);
        if(data!=null){
            configs = JSONObject.parseObject(JSONObject.toJSONString(data), Map.class);
        }else{
            configs=new HashMap<>();
        }
        /** 按钮信息 **/
        configs.put("btns",fromCrudBtnsService.selectFromCrudBtnsByBuildKey(buildKey));

        return AjaxResult.success(configs);
    }


    /**
     * 获取平台全量json信息
     * @return
     * @throws Exception
     */
    @GetMapping("/plat/fullInfo")
    public AjaxResult getPlatFormFullInfo() throws Exception {
        /**
         * 结果
         */
        Map<String,Object> result = new HashMap<>();
        //菜单全量信息
        List<SysMenu> sysMenus = menuService.selectMenuTreeByType("2");
        if(sysMenus!=null && sysMenus.size()>0){
            result.put("menu",JSONArray.parseArray(JSONObject.toJSONString(sysMenus), SysMenuVo.class));
        }
        //获取需要生成设计表单的信息
        List<GenForm> needGenFromInfo = genTableService.getNeedGenFromInfo();
        if(needGenFromInfo!=null){
            result.put("needGenFrom",JSONArray.parseArray(JSONObject.toJSONString(needGenFromInfo), GenFormVo.class));
        }
        //表单配置全量信息
        Map allBuildInfo = fromBuildConfigServiceImpl.getAllBuildInfo();
        if(allBuildInfo!=null){
            result.putAll(fromBuildConfigServiceImpl.getAllBuildInfo());
        }
        //按钮信息
        result.put("button",fromCrudBtnsService.getAllBuildKeyInfo());
        //角色绑定菜单信息
        List<SysRole> sysRoles = roleService.getAllRoleMenuInfo();
        result.put("roleMenu",JSONArray.parseArray(JSONObject.toJSONString(sysRoles), SysRoleVo.class));
        //用户绑定角色智能体  考虑是否移除，改为可以创建角色
//        result.put("userRole",JSONArray.parseArray(JSONObject.toJSONString(sysRoles), SysRoleVo.class));
        return AjaxResult.success(result);
    }
}
